package com.like.entity;

import android.app.Activity;
import android.app.DialogFragment;
import android.content.Context;
import android.os.Handler;
import android.support.v4.app.Fragment;

import org.xutils.DbManager;
import org.xutils.x;

public class BaseM {

    public Context mContext;

    protected DbManager mDbManager;

    private Activity mActivity;
    private DialogFragment mLoadingDialog;
    private Handler mHandler;
    private Runnable mShowLoadingRunnable;
    private String mTag = "";

    public BaseM(Activity activity) {
        mContext = activity;
        mHandler = new Handler();
        this.mActivity = activity;
        this.mTag = activity.getClass().getName();
        mShowLoadingRunnable = new Runnable() {
            @Override
            public void run() {
                try {
                    showLoading(true);
                } catch (Exception e) {
                }
            }
        };
    }

    public BaseM(Fragment fragment) {
        this(fragment.getActivity());
        this.mTag = fragment.getClass().getName();
    }

    public DbManager getDbManager() {
        if (mDbManager == null) {
            DbManager.DaoConfig daoConfig = new DbManager.DaoConfig();
            mDbManager = x.getDb(daoConfig);
        }
        return mDbManager;
    }

    public DbManager getDbManager(String dbName) {
        if (mDbManager == null) {
            DbManager.DaoConfig daoConfig = new DbManager.DaoConfig()
                    .setDbName(dbName);
            mDbManager = x.getDb(daoConfig);
        }
        return mDbManager;
    }

    public void setLoadingDialog(DialogFragment loadingDialog) {
        this.mLoadingDialog = loadingDialog;
    }

    public void showLoading(boolean show) {
        try {
            if (mLoadingDialog == null)
                return;
            if (show) {
                if (!mLoadingDialog.isAdded())
                    mLoadingDialog.show((mActivity)
                            .getFragmentManager(), mTag);
            } else {
                mHandler.removeCallbacks(mShowLoadingRunnable);
                if (mLoadingDialog != null
                        && mLoadingDialog.getDialog() != null
                        && mLoadingDialog.isAdded())
                    mLoadingDialog.dismiss();
            }
        } catch (Exception e) {
        }
    }

    public void showLoading(boolean show, long delayTime) {
        try {
            if (show)
                mHandler.postDelayed(mShowLoadingRunnable, delayTime);
            else {
                mHandler.removeCallbacks(mShowLoadingRunnable);
                showLoading(false);
            }
        } catch (Exception e) {
        }
    }

}
